﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebShopData;

namespace WebShop_Project
{
    public partial class Kassa : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (Session["ShoppingCart"] != null)
            {
                List<ShoppingCartItem> shoppingCartItems = (List<ShoppingCartItem>)Session["ShoppingCart"];
                GridViewCart.DataSource = shoppingCartItems;
                GridViewCart.DataBind();
            }
        }

        protected void ButtonSendOrder_Click(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                Order order = new Order
                {
                    UserID = int.Parse(Session["UserID"].ToString()),
                    FirstName = TextBoxFirstName.Text.Trim(),
                    LastName = TextBoxLastName.Text.Trim(),
                    Address = TextBoxAddress.Text.Trim(),
                    ZipCode = TextBoxZipCode.Text.Trim(),
                    Email = TextBoxEmail.Text.Trim(),
                    City = TextBoxCity.Text.Trim()
                };

                List<ShoppingCartItem> shoppingCartItems = (List<ShoppingCartItem>)Session["ShoppingCart"];
                foreach (ShoppingCartItem shoppingCartItem in shoppingCartItems)
                {
                    order.OrderRows.Add
                       (
                           new OrderRow
                               (
                                   articleID: shoppingCartItem.Article.ArticleID,
                                   quantity: shoppingCartItem.Quantity
                               )
                       );
                }

                int succesfullyAddedOrder = Orders.AddOrderToDB(order);
                if (succesfullyAddedOrder != 0)
                {
                    Session["OrderID"] = succesfullyAddedOrder;
                    Response.Redirect(string.Format("http://{0}:{1}/Orderbekräftelse.aspx", Request.Url.Host, Request.Url.Port));
                }
            }
        }

        protected void GridViewCart_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            List<ShoppingCartItem> shoppingCartItems = (List<ShoppingCartItem>)Session["ShoppingCart"];
            shoppingCartItems.RemoveAt(e.RowIndex);
            GridViewCart.DataSource = shoppingCartItems;
            GridViewCart.DataBind();
        }

    }
}